package com.fyzk.activity.forum;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/6.
 *
 * 全部话题
 */

@ContentView(R.layout.ac_forumtopiclist)
public class ForumListActivity extends BaseActivity implements RefreshListView.OnRefreshListener {

    @ViewInject(R.id.forum_topiclist_topview)
    private TopTitleView topView;

    @ViewInject(R.id.forum_topiclist_parent_listview)
    private ListView parent_listView;
    private ForumParentTopicAdapter parentTopicAdapter;
    private List<ForumParentTopicBean> parentTopicInfos = new ArrayList<>();

    private int parent_id = 0;
    @ViewInject(R.id.forum_topiclist_child_listview)
    private RefreshListView child_listView;
    private ForumChildTopicAdapter childTopicAdapter;
    private List<ForumChildTopicBean.ChildTopicBean> childTopicInfos = new ArrayList<>();
    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新
    private int page = 1;
    private int count = 10;

    private boolean isRequesting = false;   // 是否正在请求网络（点击关注时启用, 防止频繁点击）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        getParentTopicList();
    }

    private void initView() {
        topView.setOnTitleClickListener(this);

        parentTopicAdapter = new ForumParentTopicAdapter();
        parent_listView.setAdapter(parentTopicAdapter);

        child_listView.setItemsCanFocus(false);
        child_listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        child_listView.setOnRefreshListener(this);
        childTopicAdapter = new ForumChildTopicAdapter();
        child_listView.setAdapter(childTopicAdapter);

        child_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (child_listView.isDownPull){
                    return;
                }
                if (i > 0 && i <= childTopicInfos.size()) {
                    Intent intent = new Intent(getContext(), TopicListActivity.class);
                    intent.putExtra("topic_id", childTopicInfos.get(i-1).getTopic_id());
                    intent.putExtra("title", childTopicInfos.get(i-1).getTopic_title());
                    startActivity(intent);
                }

            }
        });
    }

    /**
     *  获取话题父列表（论坛）
     */
    private void getParentTopicList() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_PARENTTOPICLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_PARENTTOPICLIST, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取话子列表（论坛）
     */
    private void getChildTopicList(int parent_id, boolean showProgress) {
        this.parent_id = parent_id;
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("parent_id", parent_id);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_CHILDTOPICLIST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_CHILDTOPICLIST, params, showProgress);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  关注/取消关注（论坛）
     */
    private void requestFoucs(int topic_id) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("topic_id", topic_id);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_FOCUSCLICK);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_FOCUSCLICK, params, false);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FORUM_PARENTTOPICLIST:
                parentTopicInfos = JSON.parseArray(resultBean.getData(), ForumParentTopicBean.class);
                if (parentTopicInfos != null) {
                    for (ForumParentTopicBean item : parentTopicInfos) {
                        if (item.getTopic_id() == 2) {  // 热门
                            item.isCheck = true;
                            getChildTopicList(item.getTopic_id(), false);
                        }
                    }
                }
                parentTopicAdapter.notifyDataSetChanged();
                break;
            case CommandUtil.FORUM_CHILDTOPICLIST:
                ForumChildTopicBean childTopicBean = JSON.parseObject(resultBean.getData(), ForumChildTopicBean.class);

                List<ForumChildTopicBean.ChildTopicBean> beans = childTopicBean.getChild_topic();
//                if (requestType) {  // 加载更多
//                    if (beans.size() > 0) {
//                        childTopicInfos.addAll(beans);
//                        child_listView.hideFooterView();
//                    } else {
//                        child_listView.noMore();
//                    }
//                } else {
//                }
                childTopicInfos = beans;
                child_listView.hideHeaderView();
//                if (childTopicInfos.size() == 0) {
//                }
                child_listView.noMore();
                childTopicAdapter.notifyDataSetChanged();
                requestType = false;

                break;
            case CommandUtil.FORUM_FOCUSCLICK:
                isRequesting = false;
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode) {
        super.onFailure(requestCode);
        if (!requestType) { // 下拉刷新或第一次请求
            childTopicInfos.clear();

        } else {    // 加载更多
            child_listView.noMore();

        }
        childTopicAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDownPullRefresh() {
        page = 1;
        requestType = false;
        getChildTopicList(parent_id, true);
    }

    @Override
    public void onLoadingMore() {
        requestType = true;
//        page++;
//        getChildTopicList(parent_id, false);
    }

    class ForumParentTopicAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return parentTopicInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return parentTopicInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ForumParentTopicBean info = parentTopicInfos.get(position);
            ParentViewHolder holder;
            if (convertView == null) {
                holder = new ParentViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_forum_topiclist_parent, null);
                holder.checkBox = (RadioButton) convertView.findViewById(R.id.forum_topiclist_parent_check);
                convertView.setTag(holder);
            } else {
                holder = (ParentViewHolder) convertView.getTag();
            }

            holder.checkBox.setChecked(info.isCheck);
            holder.checkBox.setText(info.getTopic_title());
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (parentTopicInfos.get(position).isCheck) {
                        return;
                    }
                    for (ForumParentTopicBean item : parentTopicInfos) {
                        item.isCheck = false;
                    }
                    parentTopicInfos.get(position).isCheck = true;
                    parentTopicAdapter.notifyDataSetChanged();
                    LogUtil.d("check:"+parentTopicInfos.get(position).isCheck);
                    page = 1;
                    getChildTopicList(parentTopicInfos.get(position).getTopic_id(), false);
                }
            });

            return convertView;
        }
    }

    class ParentViewHolder {
        RadioButton checkBox;
    }

    class ForumChildTopicAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return childTopicInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return childTopicInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ForumChildTopicBean.ChildTopicBean info = childTopicInfos.get(position);
            final ChildViewHolder holder;
            if (convertView == null) {
                holder = new ChildViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_forum_topiclist_child, null);
                holder.icon = (ImageView) convertView.findViewById(R.id.forum_topiclist_child_icon);
                holder.title = (TextView) convertView.findViewById(R.id.forum_topiclist_child_title);
                holder.focus_checkBox = (CheckBox) convertView.findViewById(R.id.forum_topiclist_child_focus);
                holder.description = (TextView) convertView.findViewById(R.id.forum_topiclist_child_description);
                convertView.setTag(holder);
            } else {
                holder = (ChildViewHolder) convertView.getTag();
            }

            holder.title.setText(info.getTopic_title());
            holder.description.setText(info.getTopic_description());
            Glide.with(getContext()).load(info.getTopic_pic())
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .into(holder.icon);

            if (info.isCheck) {
                holder.focus_checkBox.setChecked(true);
                holder.focus_checkBox.setText("已关注");
            } else {
                holder.focus_checkBox.setChecked(false);
                holder.focus_checkBox.setText("+关注");
            }
            holder.focus_checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!MySharedPreferences.getInstance().getLoginStatus()) {
                        holder.focus_checkBox.setChecked(false);
                        AppLotteryInfos.clear();
                        ViewCallBack.getInstance().countDownObjs.clear();
                        ActivityTaskManager.getInstance().closeAllActivity();
                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    if (isRequesting) {
                        return;
                    }
                    isRequesting = true;
                    info.isCheck = !info.isCheck;
                    requestFoucs(info.getTopic_id());
                    childTopicAdapter.notifyDataSetChanged();
                }
            });

            return convertView;
        }
    }

    class ChildViewHolder {
        ImageView icon;
        TextView title;
        CheckBox focus_checkBox;
        TextView description;
    }


}
